package cn.wanho.util;


import cn.wanho.dto.CmsUser;

import io.jsonwebtoken.Claims;
import io.jsonwebtoken.JwtBuilder;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;

import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;
import java.util.Base64;
import java.util.Date;

public class JWTUtil {


    // 有效期 24小时
    public static final Long JWT_TTL = 1000 * 60 * 60 * 24L;

    // JWT令牌信息
    public static final String JWT_KEY = "qzw";

    //创建jwt字符串
    public static String createJWT(CmsUser cmsUser, String subject, Long ttlMillis) {
        //使用了hs256加密
        SignatureAlgorithm signatureAlgorithm = SignatureAlgorithm.HS256;
        //获得当前的时间
        long nowMillis = System.currentTimeMillis();
        Date now = new Date(nowMillis);
        //ttlMillis 过期时间
        if (ttlMillis == null) {
            ttlMillis = JWT_TTL;
        }

        //通过当前时间和要过期的时间进行累加，得到要过期的时间节点
        long expMillis = nowMillis + ttlMillis;
        Date expDate = new Date(expMillis);

        SecretKey secretKey = generalKey();

        JwtBuilder builder = Jwts.builder()
                .setId(cmsUser.getId()+"")                      // 设置jwt的唯一编号
                .setSubject(subject)            // 设置主题 可以是JSON数据
                .setIssuer("iu")
                .setIssuedAt(now)               // 设置签发日期
                .setExpiration(expDate)         // 设置过期时间
                //claim payload中用来绑定当前用户的信息  可以直接把一个对象丢进去都可以
                // 类似于session.setAttribute("user",user)
                .claim("id",cmsUser.getId())
                .claim("name",cmsUser.getUsername())
                .claim("icon",cmsUser.getIcon())
                // 设置签名 使用HS256算法 并设置SecretKey(字符串)
                .signWith(SignatureAlgorithm.HS256, secretKey);
        return builder.compact();


    }

    /**
     * 生成加密secretKey
     * @return
     */
    public static SecretKey generalKey() {
        byte[] encodedKey = Base64.getEncoder().encode(JWT_KEY.getBytes());
        SecretKey key = new SecretKeySpec(encodedKey, 0, encodedKey.length, "AES");
        return key;
    }

    /**
     * 解析令牌payload数据
     */
    public static Claims parseJWT(String jwtToken) throws Exception {
        SecretKey secretKey = generalKey();
        return Jwts.parser()
                .setSigningKey(secretKey)
                .parseClaimsJws(jwtToken)
                .getBody();
    }

    /**
     * 判断jwt是否有效
     * @param jwtToken
     * @return
     */
    public static boolean checkToken(String jwtToken) {
        if(null == jwtToken || "".equals(jwtToken)) {
            return false;
        }
        try {
            Jwts.parser().setSigningKey(JWT_KEY).parseClaimsJws(jwtToken);
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
        return true;
    }


    //尝试实现jwt
    public static void main(String[] args) throws Exception {
        //创建一个jwt
//        User user = new User(1,"majian","男","123456");
//        System.out.println(JWTUtil.createJWT(user,"userinfo",null));

        //查看该jwt是否存在
        String jwt = "eyJhbGciOiJIUzI1NiJ9.eyJqdGkiOiIxIiwic3ViIjoidXNlcmluZm8iLCJpc3MiOiJqYXNvbiIsImlhdCI6MTY1NjkyMDU3OSwiZXhwIjoxNjU3MDA2OTc5LCJpZCI6MSwidXNlciI6Im1hamlhbiJ9.Dhv2Djaw50QKO2Hr54629jsWWqswywgtkZrmMCwvI5I";
     //   System.out.println(JWTUtil.parseJWT(jwt));
        Claims claims = JWTUtil.parseJWT(jwt);

        System.out.println(claims);
        System.out.println(claims.get("id"));
        System.out.println(claims.get("user"));

        //     System.out.println(JWTUtil.checkToken(jwt));

    }
}
